import React from 'react';
import { Button, Toast, Modal, Checkbox, Accordion, DatePicker, List } from 'antd-mobile';
import Block from 'fs-flex'
import styles from './index.less';
import Select from '../../components/Select/index'
import Canstant from '../../utils/constant'
import PaihaoService from '../../services/paihaoService';
import CurrentPosition from '../../assets/img/current.png';
import DateUtil from '../../utils/dateUtil'
import Header from '../../components/Header/index';
import Constant from '../../utils/constant';
import paihaoService from '../../services/paihaoService';
import Audio from '../../utils/Audio';
import AudioPlay from './audio'

const alert = Modal.alert;
const CheckboxItem = Checkbox.CheckboxItem;

let theAudio = null

const statusDic = { '1': '已预约', '2': '短信已发送', '3': '已分配 ', '4': '开始服务', '5': '服务完成', '6': '跳过', '7': '超时', '8': '用户取消', '9': '终止', 'called': '已经呼叫' }
class Business extends React.Component {
    state = {
        businessType: new Map(),
        auto: null,// 语音
        currentServiceItem: null,//当前服务客户
        currentStatus: null,
        audioUrl: '',
        todoList: [],//业务类型
        businessTypes: [],//业务类型字典集合
        currentUser: null,// 当前登录用户信息

        queue: [],// 预约号队列
        queueList: [],
        temporaryQueueList: [],//临时队列
        currentDay: null,//当前查看排队日期
        activtionAccordion: {//当前激活的Accordion
            parentStart: null, //Accordion panel,取开始时间/或者临时排号
            childQueueNo: null//当前选中的子条目QueueNo
        },
        callBtnAble:true,// 呼叫按钮是否允许点击

    }
    componentWillMount() {
        this.setState({
            currentDay: new Date()
        })
    }
    async componentDidMount() {
        this.isLogin()
        const { code, data } = await PaihaoService.queryBusinessType()
        if (code === Canstant.responseOK) {
            this.setState({ businessTypes: data })
        }
        setTimeout(() => {
            this.dispatch()
            this.queryQueueList()
            this.queryTemporaryQueueList()
        }, 100);

        console.log(this.state.currentUser)
    }

    async queryQueueList() {
        const { businessType, currentDay } = this.state
        const busiTypeList = []
        if (businessType && businessType.size > 0) {
            for (var [key, value] of businessType) {
                busiTypeList.push(value)
            }
        }
        const { code, data } = await PaihaoService.loadingAble(false).queueList({
            businessIdList: busiTypeList,
            date: DateUtil.dateFtt('yyyy-MM-dd', currentDay)
        });
        if (Constant.responseOK === code) {
            this.setState({ queueList: data })
        }
    }

    queryTemporaryQueueList = async () => {
        const { businessType, currentDay } = this.state
        const busiTypeList = []
        if (businessType && businessType.size > 0) {
            for (var [key, value] of businessType) {
                busiTypeList.push(value)
            }
        }
        const { code, data } = await PaihaoService.loadingAble(false).queryTemporaryQueueList({
            businessIdList: busiTypeList,
            date: DateUtil.dateFtt('yyyy-MM-dd', currentDay)
        })
        if (Constant.responseOK === code) {
            this.setState({ temporaryQueueList: data })
        }
    }
    // 判断用户是否登录
    async isLogin() {
        let self = this
        const token = localStorage.getItem('token')
        console.log(`token:${token}`)
        if (!token) {
            this.login()
        }
        if (token && !this.state.currentUser) {
            // 查询用户当前登录用户信息，并设置到currentUser变量
            const res = await PaihaoService.getAccountByToken(token)
            if (res && res.code === Canstant.responseOK) {
                this.setState({ currentUser: res.data })
            } else {
                this.login()
            }
        }
    }
    login() {
        Toast.fail('请登录！', 5)
        setTimeout(() => {
            this.props.history.push('/manage/paihao')
        }, 1000);
    }

    //业务类型选中监听
    businessTypeSelcetChange = (index, val) => {
        this.isLogin()

        const { businessType } = this.state
        if (businessType.has(index)) {
            businessType.delete(index)
        } else {
            businessType.set(index, val)
        }
        this.setState({ businessType })
        setTimeout(() => {
            this.dispatch()
            this.queryQueueList()
            this.queryTemporaryQueueList()
        }, 300);
    }
    //下一位
    nextService(item) {
        this.isLogin()
        this.setState({ currentServiceItem: item, currentStatus: 'getready' })
    }
    // 业务员选中要处理的预约号
    async handlerSelectItem(busiItem, selectParentTitle) {
        if (!this.state.currentUser) {
            this.login()
            return
        }
        const { currentServiceItem, currentStatus } = this.state
        // 判断当前是否有正在处理的客户
        if (currentServiceItem && currentStatus === '4') {
            Toast.fail('当前窗口有正在处理的客户，服务完成后可继续选择！', 4)
            return
        }
        if (currentServiceItem && currentServiceItem.queueCode === busiItem.queueCode) {// 判断是否点击同一条
            return
        }
        const createTime = DateUtil.dateFtt('yyyy-MM-dd', new Date(busiItem.createTime))
        const currentDay = DateUtil.dateFtt('yyyy-MM-dd', this.state.currentDay)

        let dispatchId = -1
        if (currentServiceItem) {
            dispatchId = currentServiceItem.id
        }
        const { code, data } = await paihaoService.dispatchAndSkipCurrentItem(dispatchId, busiItem.id, this.state.currentUser.id)
        if (code === Canstant.responseOK) {
            this.setState({
                currentServiceItem: data,
                currentStatus: '3',
            })
            this.setAccordionCurrentActivation(selectParentTitle, busiItem.queueCode)
        }
    }
    //呼叫
    async call() {
        this.isLogin()

        Toast.info('正在叫号...', 25)
        const { currentStatus, currentServiceItem, currentUser } = this.state
        const windowNum = currentUser.windowName
        if (!currentServiceItem || (currentStatus !== "getready" && currentStatus !== "3" && currentStatus !== "called")) {
            console.log(currentServiceItem, currentStatus)
            Toast.fail('请选择客户，然后开始呼叫')
            return
        }
        let { code, data } = await PaihaoService.call(`请 ${currentServiceItem.queueCode} 号到${windowNum}办理业务`)
        let url = ''
        if (code === Canstant.responseOK) {
            this.setState({ currentStatus: 'called' })
            if (data) {
                data = data.replace(/\\/g, "/")
            }
            url = Canstant.host + data
            this.setState({
                callBtnAble:false
            },()=>{
                setInterval(()=>{
                    this.setState({
                        callBtnAble:true
                    })
                },7000)
            })
            AudioPlay.loadAudioFile(url)
        } else {
            Toast.fail('叫号异常！', 5)
        }
    }

    request (url) {
        return new Promise (resolve => {
            let xhr = new XMLHttpRequest();
            xhr.open('GET', url);
            // 这里需要设置xhr response的格式为arraybuffer
            // 否则默认是二进制的文本格式
            xhr.responseType = 'arraybuffer';
            xhr.onreadystatechange = function () {
                // 请求完成，并且成功
                if (xhr.readyState === 4 && xhr.status === 200) {
                    resolve(xhr.response);
                }
            };
            xhr.send();
        });
    }

    play(context, decodeBuffer) {
        // 调用resume恢复播放
        context.resume();
        let source = context.createBufferSource();
        source.buffer = decodeBuffer;
        source.connect(context.destination);
        // 从0s开始播放
        source.start(0);
    }

    async playAudio (context, url) {
        let audioMedia = await this.request(url);
        context.decodeAudioData(audioMedia, decode => this.play(context, decode));
    }


    // 设置当前服务状态
    async busiServerStatusManage(type) {
        const currentServiceItem = this.state.currentServiceItem
        if (!currentServiceItem) {
            Toast.fail('当前无客服务客户')
            return
        }
        const { code } = await PaihaoService.busiServerStatusManage(currentServiceItem.id, this.state.currentUser.id, type)
        if (code != Canstant.responseOK) {
            Toast.fail('操作失败，请重试！', 15)
        }
    }

    //停止播放音频
    stopVoice = () => {
        let { audio } = this.state
        if (audio != null) {
            audio.state = 2;
            audio.pause();
        }
    }

    //重置音频缓存队列和播放对象，若音频正在播放，则暂停当前播放对象，创建并使用新的播放对象
    resetVoice() {
        let { audio } = this.state
        if (audio != null) {
            audio.pause();
        }
        audio = new Audio();
        this.setState(audio)
    }

    //开始服务
    serviceBegin = () => {
        this.isLogin()
        // 设置当前状态为：已通知
        Toast.info('开始服务...', 25)
        this.setState({ currentStatus: '4' })
        this.busiServerStatusManage('4')

    }

    //服务完成
    serviceOver = () => {
        this.isLogin()

        // 设置当前状态为：处理完成
        this.busiServerStatusManage('5')
        // Toast.info('当前客户处理完成!', 25)
        setTimeout(() => {
            this.setState({ currentStatus: null, currentServiceItem: null })
            this.dispatch()
        }, 500);
        setTimeout(() => {
            this.queryQueueList()
            this.queryTemporaryQueueList()
        }, 100);
    }

    // 选中当前日期改变
    dateChange = (date) => {
        this.setState({
            currentDay: date
        })
        setTimeout(() => {
            this.dispatch()
            this.queryQueueList()
            this.queryTemporaryQueueList()
        }, 100);
    }
    //取消该预约
    serviceSkip = async () => {
        this.isLogin()

        const code = this.state.currentServiceItem.queueCode
        alert('跳过该预约服务', `跳过的号码，不再自动分，需要手动点击才能办理,确定要跳过${code}号吗？`, [
            { text: '再想想', onPress: () => console.log('cancel'), style: 'default' },
            {
                text: '确定', onPress: () => {
                    // 设置当前状态为：业务人员取消
                    this.busiServerStatusManage('6')
                    this.setState({ currentStatus: null, currentServiceItem: null })
                    setTimeout(() => {
                        this.dispatch()
                        this.queryQueueList()
                        this.queryTemporaryQueueList()
                    }, 300);
                }
            },
        ]);
    }

    // 给窗口分配一个号为已分配
    dispatch = async () => {
        this.isLogin()
        const { businessType,currentServiceItem,currentDay } = this.state
        const busiTypeList = []
        if (businessType && businessType.size > 0) {
            for (var [key, value] of businessType) {
                busiTypeList.push(value)
            }
        }
        if (!this.state.currentUser) {
            this.login()
        } else {
            const windowId = this.state.currentUser.id
            const { code, data } = await paihaoService.dispatch({
                windowId: windowId,
                busiIdList: busiTypeList,
                dateTime:currentDay
            });
            if (code === Canstant.responseOK) {
                if (data && data.queueInfo) {
                    if(!currentServiceItem){
                        this.setState({ 
                            currentServiceItem: data.queueInfo, 
                            currentStatus: '3',
                            activtionAccordion:{
                                parentStart:this.getTimeSlot(data.queueInfo),
                                childQueueNo: data.queueInfo.queueCode
                            }
                        })
                    }else if(currentServiceItem.queueCode!==data.queueInfo.queueCode){
                        this.setState({ 
                            currentServiceItem: data.queueInfo, 
                            currentStatus: '3',
                            activtionAccordion:{
                                parentStart:this.getTimeSlot(data.queueInfo),
                                childQueueNo: data.queueInfo.queueCode
                            }
                         })
                    }
                } else {
                    this.setState({ currentServiceItem: null })
                    Toast.fail('暂无可继续服务客户，可在列表中选择需要处理的客户！', 3)
                }

            } else {
                Toast.fail('操作失败，请重试！', 3)
            }
        }

    }

    getTimeSlot=(data)=>{
        console.log('getTimeSlot:',data)
        let strTimeInterval=''
        if(data.queueType && "FIXED"===data.queueType){
            return data.timeSlotStartStart

        }
        return "lsh"
    }

    // 设置当前展开的手风琴条目
    reSetAccordionCurrentActivation = () => {
        const { queueList, temporaryQueueList, currentServiceItem } = this.state
        if (currentServiceItem) {
            if (queueList && queueList.length > 0) {
                queueList.map((item, index) => {
                    if (item.queueInfoList && item.queueInfoList.length > 0) {
                        const queues = item.queueInfoList.filter(queueItem => queueItem.queueNo === currentServiceItem.queueCode)
                        if (queues && queues.length > 0) {
                            this.setAccordionCurrentActivation(item.startTime, currentServiceItem.queueCode)
                        }
                    }
                })
            } else if (temporaryQueueList && temporaryQueueList.length > 0) {
                const queues = temporaryQueueList.filter(item => item.queueCode === currentServiceItem.queueCode)
                if (queues && queues.length > 0) {
                    this.setAccordionCurrentActivation('临时排号', currentServiceItem.queueCode)
                }
            }
        }
    }

    setAccordionCurrentActivation = async (parentStart, childQueueNo) => {
        // 设置当前展开
        this.setState({
            activtionAccordion: {//当前激活的Accordion
                parentStart: parentStart, //Accordion panel,取开始时间/或者临时排号
                childQueueNo: childQueueNo//当前选中的子条目position
            }
        })
    }

    componentWillUnmount() {
        if (theAudio) {
            theAudio = null
        }
    }

    // 获取当前处理号的预约时段或者临时号信息
    getTimeInterval=()=>{
        const {timeSlotStartStart,timeSlotStartEnd,queueType}=this.state.currentServiceItem
        let strTimeInterval=''
        console.log(`timeSlotStartStart:${timeSlotStartStart}  timeSlotStartEnd:${timeSlotStartEnd}`)
        if(queueType && "FIXED"===queueType){
            // 固定预约号
            if(timeSlotStartStart){
                strTimeInterval+=timeSlotStartStart
            }
            if(timeSlotStartEnd){
                strTimeInterval+=('-'+timeSlotStartEnd)
            }
            return strTimeInterval

        }
        return "临时号"
    }

    // 选择业务类型checkbox
    renderBusinessCheckBox = (selectType, typeDatas, handler) => {
        return <Block mt={10} f={1} >
            {
                typeDatas && typeDatas.length > 0 ? typeDatas.map((item, index) => {
                    const isChecked = selectType.has(item.id)
                    return <Block className={styles.selectItem} f={1} key={'business-' + index}>
                        <CheckboxItem checked={isChecked} onChange={() => handler(item.id, item.id)}>
                            {item.busitype}
                        </CheckboxItem>
                    </Block>
                }) : <Block f={1} a='c' j='c'>暂无类型</Block>
            }
        </Block>
    }

    // 渲染当前服务客户信息
    renderCurrentItemView = () => {
        const { currentServiceItem, currentStatus,callBtnAble } = this.state

        if (currentServiceItem && currentServiceItem != null) {
            const callAble = currentServiceItem && currentStatus !== '4' && currentStatus !== '5' && callBtnAble//是否允许呼叫
            const beginServiceAble = currentServiceItem && currentStatus === 'called';//状态为已呼叫
            const overServiceAble = currentServiceItem && currentStatus === '4';//状态为处理中
            const cancelServiceAble = currentServiceItem && (currentStatus === '3' || currentStatus === 'called');//状态为处理中
            return <Block vf p={10} className={styles.userInfoBox}>

                <Block h={50} fs={25} wf>
                    {/* <Block f={1}>{currentServiceItem.queueNo}</Block> */}
                    <Block f={1} a='c' j='c' style={{ color: 'red' }}>{currentServiceItem.queueCode}</Block>
                    <Block fs={10} a='c' j='c' w={100}><Button style={{ width: '100px' }} disabled={!cancelServiceAble} onClick={this.serviceSkip.bind(this)} size='small' type="primary">跳过</Button></Block>
                </Block>
                <Block mt={10} fs={14} style={{ color: 'red' }}>{currentServiceItem.notifyInfo ? currentServiceItem.notifyInfo : null}</Block>
                <Block hf h={35} a='c'>
                    <Block f={1} hf j='c' a='c'>
                        <Block fs={14} w={70}>联系人:</Block>
                        <Block fs={12} f={1}>{currentServiceItem.name ? currentServiceItem.name : null}</Block>
                    </Block>
                </Block>
                <Block hf h={35} a='c'>
                    <Block f={1} hf j='c' a='c'>
                        <Block fs={14} w={70}>联系电话:</Block>
                        <Block fs={12} f={1}>{currentServiceItem.mobile ? currentServiceItem.mobile : null}</Block>
                    </Block>
                </Block>
                <Block hf h={35}>
                    <Block f={1} hf j='c' a='c'>
                        <Block fs={14} w={70}>业务类型:</Block>
                        <Block fs={12} f={1}>{currentServiceItem.businessName ? currentServiceItem.businessName : null}</Block>
                    </Block>
                </Block>

                <Block hf h={35}>
                    <Block f={1} hf j='c' a='c'>
                        <Block fs={14} w={70}>预约时段:</Block>
                        <Block fs={12} f={1}>{this.getTimeInterval()}</Block>
                    </Block>
                </Block>

                <Block hf h={35}>
                    <Block f={1} hf>
                        于{currentServiceItem.createTime ? DateUtil.dateFtt('yyyy-MM-dd hh:mm:ss', new Date(currentServiceItem.createTime)) : ''} 预约
                </Block>
                </Block>
                <Block hf h={35}>
                    <Block f={1} fs={10}><Button size='small' disabled={!callAble} onClick={this.call.bind(this)} type="primary">呼叫</Button></Block>
                    <Block f={1} fs={10} ml={5}><Button disabled={!beginServiceAble} onClick={this.serviceBegin.bind(this)} size='small' type="primary">开始服务</Button></Block>
                    <Block f={1} fs={10} ml={5}><Button disabled={!overServiceAble} onClick={this.serviceOver.bind(this)} size='small' type="primary">服务完成</Button></Block>

                </Block>
                <Block a='c' j='c' mt={5}>语音解析核心技术由科大讯飞提供</Block>

                {/* <Block>
                <audio
                    controls
                    src="http://58.87.75.205:8899/2018/13/16/20181216112915.mp3">
                        Your browser does not support the
                        <code>audio</code> element.
                </audio>
                </Block> */}

                <Block style={{ display: 'none' }}>
                    <audio controls style={{ display: 'none' }} ref={(audio) => { this.audioValue = audio; }} preload="auto" autoPlay controlsList="nodownload" >
                        {/*     <source src='http://192.168.0.102:8080/audio/audio.mp3' type="audio/mpeg" /> */}
                        <code>audio</code>
                        您的浏览器不支持 audio 元素。
                </audio>
                    {/* <audio src='http://192.168.0.102:8080/audio/audio.mp3'></audio> */}
                </Block>
            </Block>
        }
        return <Block vf p={10} a='c' j='c' className={styles.userInfoBox} style={{ color: 'rgb(148, 148, 148)' }}><Block a='c' j='c'>暂无待处理客户，请选择客户开始...</Block></Block>
    }

    render() {
        const { businessType, queueList, businessTypes, temporaryQueueList, currentStatus, currentUser, activtionAccordion } = this.state
        const item = {
            bc: '#37caec',
            m: 10
        };
        const nextBtnDisableClick = (currentStatus != null || currentStatus === '2' || currentStatus === '3' || currentStatus === 'getready')
        const selectItemStyle = {
            color: '#FF8E44',
            borderBottom: '1px solid ,#FF8E44'
        }

        const ListItemHeader = (item) => {

            let count = 0
            if (item && item.queueInfoList && item.queueInfoList.length > 0) {
                count = item.queueInfoList.length
            }
            return <Block wf className={styles.listItemHeader}>
                <Block f={1} >{item.startTime}-{item.endTime}</Block>
                <Block w={150}>等待{count}人</Block>
            </Block>
        }
        console.log(activtionAccordion)
        return (
            <Block vf>
                <Block>
                    <Header history={this.props.history} title={currentUser && currentUser.windowName ? `叫号（${currentUser.windowName}）` : '叫号'} />
                </Block>
                <Block vf j='c' p={3} style={{ height: '100%' }}>
                    <Block vf>
                        <Block ml={10} mr={10}>
                            <Block mt={10} f={1}>
                                <Block fs={14}>业务类型：</Block>
                                {
                                    this.renderBusinessCheckBox(businessType, businessTypes, this.businessTypeSelcetChange)
                                }
                            </Block>
                            <Block j='a' vf mt={10}>
                                <Block fs={14} mb={5}>当前处理业务：</Block>
                                {this.renderCurrentItemView()}
                            </Block>
                            <Block mt={10} className={styles.listBox}>
                                <DatePicker
                                    mode="date"
                                    format={date => DateUtil.dateFtt('yyyy-MM-dd', date)}
                                    title="选择日期"
                                    extra="选择日期"
                                    value={this.state.currentDay}
                                    onChange={this.dateChange}
                                >
                                    <List.Item arrow="horizontal">排号队列</List.Item>
                                </DatePicker>
                                <Accordion accordion={true} defaultActiveKey={activtionAccordion.parentStart ? activtionAccordion.parentStart : null} >
                                    {                                        queueList && queueList.length > 0 ? queueList.map((listItem) =>
                                            <Accordion.Panel header={ListItemHeader(listItem)} key={listItem.startTime}>
                                                {
                                                    listItem.queueInfoList && listItem.queueInfoList.length > 0 ? listItem.queueInfoList.map((busItem, busIndex) => {

                                                        return <Block className={busIndex % 2 !== 0 ? styles.accordionItemEvennumbers : styles.accordionItem}
                                                            wf key={"busItem" + busIndex} h={30} p={5} m={5}
                                                            onClick={this.handlerSelectItem.bind(this, busItem.queueInfo, queueList.startTime)}
                                                            style={activtionAccordion.childQueueNo && activtionAccordion.childQueueNo === busItem.queueNo ? selectItemStyle : null} >
                                                            <Block f={1} a="c" >{busItem.queueNo}</Block>
                                                            <Block f={1} a="c">业务类型：{busItem.businessTypeName}</Block>
                                                        </Block>
                                                    }) : <Block fs={12} p={5}>该时段暂无预约</Block>
                                                }
                                            </Accordion.Panel>) : <Block fs={14}>暂无预约</Block>
                                    }
                                    <Accordion.Panel header={
                                        <Block wf className={styles.listItemHeader}>
                                            <Block f={1} >临时预约</Block>
                                            <Block w={150}>等待{temporaryQueueList && temporaryQueueList.length > 0 ? temporaryQueueList.length : 0}人</Block>
                                        </Block>
                                    } key='lsh'>
                                        {
                                            temporaryQueueList && temporaryQueueList.length > 0 ?
                                                temporaryQueueList.map((item, index) => {
                                                    return <Block className={index % 2 !== 0 ? styles.accordionItemEvennumbers : styles.accordionItem}
                                                        wf key={"temporaryItem" + index} h={30} p={5} m={5}
                                                        onClick={this.handlerSelectItem.bind(this, item, '临时排号')}
                                                        style={activtionAccordion.childQueueNo && activtionAccordion.childQueueNo === item.queueCode ? selectItemStyle : null} >
                                                        <Block f={1} a="c" >{item.queueCode}</Block>
                                                        <Block f={1} a="c">业务类型：{item.businessName}</Block>
                                                    </Block>
                                                })
                                                : <Block fs={12} p={5}>暂无临时预约号</Block>
                                        }
                                    </Accordion.Panel>

                                </Accordion>
                            </Block>

                        </Block>
                    </Block>
                </Block>

            </Block>
        )
    }
}

export default Business